﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 包装规格服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class PackspecificationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Packspecification> _packspecificationRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;

    public PackspecificationService(SqlSugarRepository<Packspecification> packspecificationRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _packspecificationRep = packspecificationRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询包装规格 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询包装规格")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<PackspecificationOutput>> Page(PagePackspecificationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _packspecificationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.PackCoding.Contains(input.Keyword) || u.PackName.Contains(input.Keyword) || u.PackType.Contains(input.Keyword) || u.InsideWeight.Contains(input.Keyword) || u.OuterWeight.Contains(input.Keyword) || u.PalletWeight.Contains(input.Keyword) || u.PackDescribe.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PackCoding), u => u.PackCoding.Contains(input.PackCoding.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PackName), u => u.PackName.Contains(input.PackName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PackType), u => u.PackType.Contains(input.PackType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InsideWeight), u => u.InsideWeight.Contains(input.InsideWeight.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OuterWeight), u => u.OuterWeight.Contains(input.OuterWeight.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PalletWeight), u => u.PalletWeight.Contains(input.PalletWeight.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PackDescribe), u => u.PackDescribe.Contains(input.PackDescribe.Trim()))
            .WhereIF(input.InsideLength != null, u => u.InsideLength == input.InsideLength)
            .WhereIF(input.InsideWidth != null, u => u.InsideWidth == input.InsideWidth)
            .WhereIF(input.InsideHeight != null, u => u.InsideHeight == input.InsideHeight)
            .WhereIF(input.InsideCapaCity != null, u => u.InsideCapaCity == input.InsideCapaCity)
            .WhereIF(input.OuterLength != null, u => u.OuterLength == input.OuterLength)
            .WhereIF(input.OuterWidth != null, u => u.OuterWidth == input.OuterWidth)
            .WhereIF(input.OuterHeight != null, u => u.OuterHeight == input.OuterHeight)
            .WhereIF(input.OuterCapaCity != null, u => u.OuterCapaCity == input.OuterCapaCity)
            .WhereIF(input.PalletLength != null, u => u.PalletLength == input.PalletLength)
            .WhereIF(input.PalletWidth != null, u => u.PalletWidth == input.PalletWidth)
            .WhereIF(input.PalletHeight != null, u => u.PalletHeight == input.PalletHeight)
            .WhereIF(input.PalletCapaCity != null, u => u.PalletCapaCity == input.PalletCapaCity)
            .Select<PackspecificationOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取包装规格详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取包装规格详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Packspecification> Detail([FromQuery] QueryByIdPackspecificationInput input)
    {
        return await _packspecificationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加包装规格 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加包装规格")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddPackspecificationInput input)
    {
        var entity = input.Adapt<Packspecification>();
        return await _packspecificationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新包装规格 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新包装规格")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatePackspecificationInput input)
    {
        var entity = input.Adapt<Packspecification>();
        await _packspecificationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除包装规格 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除包装规格")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletePackspecificationInput input)
    {
        var entity = await _packspecificationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _packspecificationRep.FakeDeleteAsync(entity);   //假删除
        //await _packspecificationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除包装规格 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除包装规格")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletePackspecificationInput> input)
    {
        var exp = Expressionable.Create<Packspecification>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _packspecificationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _packspecificationRep.FakeDeleteAsync(list);   //假删除
        //return await _packspecificationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出包装规格记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出包装规格记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagePackspecificationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportPackspecificationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var packTypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Package-specifications-for-mixed-package-types" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.PackTypeDictLabel = packTypeDictMap.GetValueOrDefault(e.PackType ?? "", e.PackType);
        });
        return ExcelHelper.ExportTemplate(list, "包装规格导出记录");
    }
    
    /// <summary>
    /// 下载包装规格数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载包装规格数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportPackspecificationOutput>(), "包装规格导入模板");
    }
    
    /// <summary>
    /// 导入包装规格记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入包装规格记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var packTypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Package-specifications-for-mixed-package-types" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportPackspecificationInput, Packspecification>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.PackTypeDictLabel)) continue;
                        item.PackType = packTypeDictMap.GetValueOrDefault(item.PackTypeDictLabel);
                        if (item.PackType == null) item.Error = "混包类型字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Packspecification>>();
                    
                    var storageable = _packspecificationRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.PackCoding?.Length > 32, "编码长度不能超过32个字符")
                        .SplitError(it => it.Item.PackName?.Length > 32, "名称长度不能超过32个字符")
                        .SplitError(it => it.Item.PackType?.Length > 32, "混包类型长度不能超过32个字符")
                        .SplitError(it => it.Item.InsideWeight?.Length > 32, "内箱重量长度不能超过32个字符")
                        .SplitError(it => it.Item.OuterWeight?.Length > 32, "外箱重量长度不能超过32个字符")
                        .SplitError(it => it.Item.PalletWeight?.Length > 32, "栈板重量长度不能超过32个字符")
                        .SplitError(it => it.Item.PackDescribe?.Length > 32, "描述长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
